package com.sam.im.heiqun.uis.activities;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.utils.CashierInputFilter;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.text.PasswordEditText;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/1/8.
 * 发送普通红包
 * 由于设置状态栏颜色，这里继承Activity
 */
public class SendOrdinaryRedPacket extends BaseSwipeBackActivity implements View.OnClickListener {

    private static final String TAG = SendOrdinaryRedPacket.class.getSimpleName();
    @BindView(R.id.edit_sendMoney)
    EditText sendMoney;
    @BindView(R.id.edit_message)
    EditText edit_message;
    @BindView(R.id.send)
    Button send;
    @BindView(R.id.sum_money)
    TextView sum_money;
    @BindView(R.id.pre_tv_title)
    TextView title;
    @BindView(R.id.tv_balance)
    TextView tvBalance ;
    PGService mPgService;
    private Long destid;

    private AlertDialog payDialog;
    private PasswordEditText payPSD;
    private PGService mPGservice;
    private double balance;

    /**
     * 设置状态栏颜色用
     */
    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public void init() {
        mPGservice = PGService.getInstance();
        send.setEnabled(false);
        title.setText(getResources().getString(R.string.send_red_package));
        InputFilter[] filters = {new CashierInputFilter()};//限定输入为金额模式
        //String userId=ToolsUtils.getMyUserId();
        //把需要传给后台的参数写成json然后加密传给后台，加密更安全
        /*com.alibaba.fastjson.JSONObject json = new JSONObject();
        json.put("userId", userId);*/
        mPGservice.getBalance(ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.net_visit_exception));
            }

            @Override
            public void onNext(String s) {
                balance = Double.parseDouble(s);
                tvBalance.setText(getResources().getString(R.string.yu_e_1)+s+getResources().getString(R.string.yuan));
            }
        });
        sendMoney.setFilters(filters);
        sendMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (null != editable && !"".equals(editable.toString()) && 0 != Double.parseDouble(editable.toString())&&Double.parseDouble(editable.toString())<=200) {
                    if (Double.parseDouble(editable.toString())>balance){
                        send.setEnabled(false);
                        send.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                        send.setText(getResources().getString(R.string.yue_nozu));
                        sum_money.setText("￥ 0.00");
                    }else {
                        send.setText(getResources().getString(R.string.send_red_package));
                        send.setBackgroundResource(R.drawable.rp_bg_circle_btn_y);
                        sum_money.setText("￥ " + editable.toString());
                        send.setEnabled(true);
                    }
                } else {
                    if (!"".equals(editable.toString())&&Double.parseDouble(editable.toString())>200){
                        send.setText(getResources().getString(R.string.one_redpacket_out200));
                    }else {
                        send.setText(getResources().getString(R.string.send_red_package));
                    }
                    send.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                    sum_money.setText("￥ 0.00");
                    send.setEnabled(false);
                }
            }
        });
    }
    @OnClick({R.id.pre_v_back, R.id.send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.send:
                doSend();
                break;
            case R.id.pay_commit:
                String pwd = payPSD.getText().toString().trim();
                if (null == pwd || "".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
                    validatePayPwd(pwd);
                }
                break;
            case R.id.pay_cancel:
                payDialog.dismiss();
                break;
        }
    }
    @Override
    public int getContentViewId() {
        return R.layout.activity_send_ordinary_redpacket;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.send_red_package);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setWindowStatusBarColor(this, R.color.red9);
        mPgService = PGService.getInstance();
        destid = getIntent().getLongExtra("destid", 0);
       /* *//**
         * 设置状态栏颜色
         *//*
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.red9);//通知栏所需颜色
        }*/
       // setContentView(R.layout.activity_send_ordinary_redpacket);
       // ButterKnife.bind(this);
        init();
    }

    /**
     * 做发送红包的逻辑操作
     */
    private void doSend() {
        showProgress(null);
        final UserEntivity user = ToolsUtils.getUser();

        if (!ToolsUtils.currentNetState(this)) {
            return;
        }
        String myUserId = ToolsUtils.getMyUserId();
        mPgService.getBalance(myUserId).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                Log.e(TAG, "onResultError: 发送个人红包，接收用户余额出错");
            }
            @Override
            public void onNext(String s) {
                hideProgress();
                Float balance = Float.valueOf(s);
                Float money = Float.valueOf(sendMoney.getText().toString().trim());
                if (money > balance) {
                    Toast.makeText(SendOrdinaryRedPacket.this, getString(R.string.balance_lack_please_recharge), Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(SendOrdinaryRedPacket.this, SelectRechargeTypeActivity.class));
                } else {
                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                       // Toast.makeText(SendOrdinaryRedPacket.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();
                        showSetPSWdialog();
                        return;
                    }
                    showPayDialog();
                }
            }
        });
    }
    private void showSetPSWdialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(SendOrdinaryRedPacket.this);
        builder.setTitle(getResources().getString(R.string.tip_psw));
        builder.setMessage(getResources().getString(R.string.no_pay_psw));
        builder.setNegativeButton(getResources().getString(R.string.now_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton(getResources().getString(R.string.now_go), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(SendOrdinaryRedPacket.this, NewPasswordActivity.class);
                intent.putExtra("type", getResources().getString(R.string.set_pay_psd));
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    /**
     * 验证支付密码
     *
     * @param pwd
     */
    private void validatePayPwd(String pwd) {
        String payPsd = MD5.MD532(pwd);
        mPGservice.validatePayPwd(payPsd, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showLongToast(getResources().getString(R.string.pay_psd_verify_defeat));
            }
            @Override
            public void onNext(String validateEntivity) {
                String money = sendMoney.getText().toString().trim();
                String liuyan = edit_message.getText().toString().trim();
                if (null == liuyan && "".equals(liuyan)) {
                    liuyan = getResources().getString(R.string.wish_you_good_fortune_and_every_success);
                }
                if (liuyan.length() > 10){
                    showToast("留言长度不能大于10");
                }
                sendRedPacket("" + destid, money, liuyan);
                payDialog.dismiss();
            }
        });
    }

    /**
     * 发送红包
     *
     * @param uId
     * @param money
     * @param liuyan
     */
    public void sendRedPacket(final String uId, final String money, final String liuyan) {
        String userId=ToolsUtils.getMyUserId();
        //要传给后台的参数全部封装成json，然后加密传给后台
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("redPacketType", "2");
        json.put("userId", userId);
        json.put("redPacketCount", "1");
        json.put("redPacketContent", liuyan);
        json.put("destId", uId);
        json.put("destType", "1");
        json.put("redPacketAmount", money);
        json.put("command", "");
        json.put("limit", "");
        String content = RequestRSAUtils.setRsaContent(json);
        mPgService.sendRedPacket(content).subscribe(new AbsAPICallback<String>() {
        //mPgService.sendRedPacket("2", ToolsUtils.getMyUserId(), "1", liuyan, uId, "1", money,"").subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(getResources().getString(R.string.send_faild));
            }

            @Override
            public void onNext(String data) {
//                new ToastUtils().showSingleToast(data);
                Intent intent = new Intent();
                intent.putExtra("destid", uId);
                intent.putExtra("money", money);
                intent.putExtra("liuyan", liuyan);
                intent.putExtra("redPacketId", data);
                setResult(10, intent);
                finish();
            }
        });
    }
    private void showPayDialog() {
        View dialog = LayoutInflater.from(this).inflate(R.layout.transfer_account_dialog, null);
        payDialog = new AlertDialog.Builder(this).setView(dialog).create();
        payDialog.show();
        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(this);
        payCommit.setOnClickListener(this);
    }

    private void popupKeyboard(final PasswordEditText editText) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }
}
